<?php 
    
namespace App\Http\Common;
use Illuminate\Support\Facades\Cache;
use DB;

/**
* 
*/
class ToolsService
{

    /**
     * 一维数据数组生成数据树
     * @param array $list 数据列表
     * @param string $id 父ID Key
     * @param string $pid ID Key
     * @param string $son 定义子数据Key
     * @return array
     */
    public static function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'sub') {
        $list = self::object_array($list);
        $tree = $map = array();
        foreach ($list as $item) {
            $map[$item[$id]] = $item;
        }
        foreach ($list as $item) {
            if (isset($item[$pid]) && isset($map[$item[$pid]])) {
                $map[$item[$pid]][$son][] = &$map[$item[$id]];
            } else {
                $tree[] = &$map[$item[$id]];
            }
        }
        unset($map);
        return $tree;
    }

    /**
    * 对象转数组
    */    
    public static function object_array($list) {

        $array = [];
        foreach ($list as $item) {
            if (is_object($item)) {
                $tmp = [];
                foreach ($item as $key => $value) {
                    $tmp[$key] = $value;
                }
                $array[] = $tmp;
            }
        }

        return $array;  
    }


    /**
     * 检查用户节点权限
     * @param string $node 节点
     * @return bool
     */
    public static function checkAuthNode($node) {
        list($module, $controller, $action) = explode('/', str_replace(['?', '=', '&'], '/', $node . '///'));
        $auth_node = strtolower(trim("{$module}/{$controller}/{$action}", '/'));
        if (session('user.username') === 'admin' || stripos($node, 'admin/index') === 0) {
            return true;
        }
        if (!in_array($auth_node, self::getAuthNode())) {
            return true;
        }
        return in_array($auth_node, (array) session('user.nodes'));
    }

    /**
    * 获取授权节点
    * @return array
    */
    public static function getAuthNode() {
        $nodes = cache('need_access_node');
        if (empty($nodes)) {
            $nodes = DB::table('system_node')->where('is_auth', '1')->select('node');
            cache::forever('need_access_node', $nodes);
        }
        return $nodes;
    }

}